from common import get_logger, browser
from DrissionPage.common import Keys

logger = get_logger(__name__)


def post_to_xhs(title, intro, tags, img_paths):
    extra_info = "无"
    try:
        tab = browser.new_tab("https://creator.xiaohongshu.com/publish/publish")
        tab.wait(2)
        tab("tag:span@text()=发布笔记").click()
        tab.wait(2)
        tab("tag:span@text()=上传图文").click()
        tab.wait(2)
        # 设置要上传的图片路径，多个路径使用换行符分隔
        tab.set.upload_files("\n".join(img_paths))
        tab.wait(2)
        # 查找点击上传图片的按钮
        print(tab("tag:span@text()=上传图片"))
        tab("tag:span@text()=上传图片").click()
        tab.wait(2)
        tab("tag:input@@type=text@@class=d-text").input(title)
        tab.wait(2)
        editor = tab(".:ql-editor")
        editor.input(intro)
        tab.wait(2)
        editor.input(Keys.ENTER, clear=False)
        print(f"标签：{tags}")
        for tag in tags:
            editor.input(f"#{tag}")
            editor.input(Keys.SPACE, clear=False)
            tab.wait(1)
        tab("tag:span@text()=发布").click()
        logger.info("小红书发布成功")
        status = 1
    except Exception as e:
        status = 2
        extra_info = str(e)
        logger.error(extra_info)
    return {
        "status": status,
        "extra_info": extra_info
    }
